# -*- coding: utf-8 -*-
import json
from flask import request, url_for, abort, redirect,flash, current_app
from flask_admin.babel import gettext, ngettext
from flask_security import current_user
from flask_admin.contrib.sqla import ModelView
from flask_admin import BaseView, expose
from flask_admin._compat import (iteritems, itervalues, OrderedDict, as_unicode, csv_encode, text_type)
from sqlalchemy import or_, and_, cast, text
from sqlalchemy.types import String
from flask_admin.contrib.sqla.tools import get_primary_key, has_multiple_pks, is_relationship, is_association_proxy
from flask_admin.contrib.sqla.ajax import QueryAjaxModelLoader
import flask_admin_toggle_control
from adminApp.extensions import redis_store, db


class MyCusView(flask_admin_toggle_control.ViewMixin, BaseView):
    def is_accessible(self):
        return (current_user.is_active and
                current_user.is_authenticated and
                current_user.has_role('superuser')
        )

    def _handle_view(self, name, **kwargs):
        """
        Override builtin _handle_view in order to redirect users when a view is not accessible.
        """
        if not self.is_accessible():
            if current_user.is_authenticated:
                # permission denied
                abort(403)
            else:
                # login
                return redirect(url_for('security.login', next=request.url))


class MyModelView(flask_admin_toggle_control.ViewMixin, ModelView):
    can_set_page_size = True
    can_create = True
    can_edit = True
    can_delete = True
    can_view_details = True
    column_default_sort = 'id'
    fast_mass_delete = True
    column_display_pk = True
    query_exclude_column_list = None
    # named_filter_urls = True
    # edit_modal = True
    # create_modal = True
    # details_modal = True

    def is_accessible(self):
        return (current_user.is_active and
                current_user.is_authenticated and
                current_user.has_role('superuser')
        )

    def _handle_view(self, name, **kwargs):
        """
        Override builtin _handle_view in order to redirect users when a view is not accessible.
        """
        if not self.is_accessible():
            if current_user.is_authenticated:
                # permission denied
                abort(403)
            else:
                # login
                return redirect(url_for('security.login', next=request.url))

    def _get_list_filter_args(self):
        if self._filters:
            filters = []
            for n in request.args:
                if not n.startswith('flt'):
                    continue

                if '_' not in n:
                    continue

                pos, key = n[3:].split('_', 1)

                if key in self._filter_args:
                    idx, flt = self._filter_args[key]
                    value = request.args[n]
                    if flt.validate(value):
                        filters.append((pos, (idx, as_unicode(flt.name), value)))
                    else:
                        flash(gettext('Invalid Filter Value: %(value)s', value=value), 'error')
            return [v[1] for v in sorted(filters, key=lambda n: n[0])]

        return None

class AjaxQueryIndexLike(QueryAjaxModelLoader):
    '''
    处理ajax查询，空字符不计入条件，使用 like xx% 查询，有索引的时候不进行扫描
    '''
    def get_list(self, term, offset=0, limit=10):
        query = self.get_query()

        # no type casting to string if a ColumnAssociationProxyInstance is given
        if term:
            filters = (field.ilike(u'%s%%' % term) if is_association_proxy(field)
                       else cast(field, String).ilike(u'%s%%' % term) for field in self._cached_fields)
            query = query.filter(or_(*filters))

        if self.filters:
            filters = [text("%s.%s" % (self.model.__tablename__.lower(), value)) for value in self.filters]

            query = query.filter(and_(*filters))

        if self.order_by:
            query = query.order_by(self.order_by)

        return query.offset(offset).limit(limit).all()


from .sysview import UserView, RoleView
from .appconfigview import AppConfigView
from .tasklogview import TaskLogView
from .machine_view import MachineView
from .netcard_view import NetworkCardView
from .idc_view import IdcView
from .broadband_account_view import BroadBandAccountView
from .hard_disk_view import HardDiskView
from .defaultnicflowdataview import DefaultNicFlowDataView
from .aqy_bandwidth_95_view import AqyBandWidth95View
from .hd_error_log_view import HdErrorLogView
from .pve_vm_conf_view import PveVmConfView
from .timed_tasks_view import TimedTasksView
from .source_aqy_bandwidth_95_view import SourceAqyBandWidth95View
from .source_my_bandwidth_95_view import SourceMyBandWidth95View
from .calc_bandwidth95_view import CalcBandWidth95View
from .show_bandwidth95_view import ShowBandWidth95View